import mongoose from 'mongoose'
import Koa from 'koa'
import bodyParser from 'koa-bodyparser'
import logger from 'koa-logger'
import route from './router'
import cors from 'koa2-cors'
import path from 'path'
import fs from 'fs'
import middleware from './middleware'

mongoose.Promise = require('bluebird')
mongoose.connect('// 数据库地址', { useNewUrlParser: true })
const models_path = path.join(__dirname, './models')

const work = modelPath => {
    fs.readFileSync(modelPath).forEach(item => {
        const filePath = path.join(modelPath, '/' + item)
        const stat = fs.statSync(filePath)

        if (stat.isFile()) {
            if (/(.*)\.(js|coffee)/.test(file)) {
                require(filePath)
            }
        } else if (stat.isDirectory()) {
            walk(filePath)
        }
    })
}

work(models_path)

const app = new Koa()

// 定义中间件
middleware(app)

// 解决跨域问题
app.use(cors())

// 指定 public目录为静态资源目录，用来存放 js css images 等
app.use(staticFiles(path.resolve(__dirname, "./public")))

app.user(bodyParser())

app.use(logger())

app.use(route.routes()).use(route.allowedMethods())


export default app